'use strict'
const fs = require('fs')
const path = require('path')
const dateFormat = require('dateformat')
const Service = require('egg').Service

class UploadService extends Service {
    async upload(stream) {
        const now = new Date();
        const timeStr = dateFormat(now, "yyyymmdd");

        let temps = stream.filename.split('.');
        const nameStr = temps[0] + now.getUTCSeconds();
        let type = temps[temps.length - 1]

        const dir = path.join(this.config.baseDir, `imageRec/${timeStr}`);
        if (!fs.existsSync(dir)) {
            fs.mkdirSync(dir);
        }
        const buffer = await this.streamToBuffer(stream);
        await fs.writeFileSync(path.join(this.config.baseDir, `imageRec/${timeStr}/${nameStr}.${type}`), buffer);

        return `/public/${timeStr}/${nameStr}.${type}`
    }

    /**
     * cnvert stream to buffer
     * @param {fileStream} stream 
     */
    streamToBuffer(stream) {
        return new Promise((resolve, reject) => {
            let buffers = [];
            stream.on('error', reject);
            stream.on('data', (data) => { buffers.push(data); });
            stream.on('end', () => { resolve(Buffer.concat(buffers)); });
        });
    }

}

module.exports = UploadService

